package com.beeb.commit.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.CommitMessageI;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl;
import com.intellij.openapi.vcs.ui.Refreshable;
import com.intellij.vcs.commit.CommitProjectPanelAdapter;
import git4idea.GitLocalBranch;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.Nullable;

/**
 * @author darekkay
 */
public class CreateCommitAction extends AnAction {

	public void actionPerformed(AnActionEvent actionEvent) {
		final CommitMessageI commitPanel = getCommitPanel(actionEvent);
		if (commitPanel == null) {
			return;
		}
		if (commitPanel instanceof CommitProjectPanelAdapter) {
			CommitProjectPanelAdapter commitProjectPanelAdapter = (CommitProjectPanelAdapter) commitPanel;
			String commitMessage = commitProjectPanelAdapter.getCommitMessage();
//			Messages.showMessageDialog(commitMessage, "Information", Messages.getInformationIcon());
			String branchName = extractBranchName(actionEvent.getProject());
			if (commitMessage.contains(branchName)) {
				return;
			}
			commitProjectPanelAdapter.setCommitMessage(commitMessage.trim() + " --" + branchName);
		}

	}

	@Nullable
	private static CommitMessageI getCommitPanel(@Nullable final AnActionEvent e) {
		if (e == null) {
			return null;
		}
		final Refreshable data = (Refreshable) Refreshable.PANEL_KEY.getData(e.getDataContext());
		if (data instanceof CommitMessageI) {
			return (CommitMessageI) data;
		}
		return (CommitMessageI) VcsDataKeys.COMMIT_MESSAGE_CONTROL.getData(e.getDataContext());
	}

	private String extractBranchName(Project project) {
		String branch = "";
		ProjectLevelVcsManager instance = ProjectLevelVcsManagerImpl.getInstance(project);
		if (instance.checkVcsIsActive("Git")) {
			GitRepository currentRepository = GitBranchUtil.getCurrentRepository(project);
			if (currentRepository != null) {
				GitLocalBranch currentBranch = currentRepository.getCurrentBranch();
				if (currentBranch != null) {
					branch = currentBranch.getName().trim();
				}
			}
		}
		return branch;
	}
}